const fileContent = async (file) => {
    const modal = document.getElementById('myModal');
    const modalText = document.getElementById('modalText');

    if (modal && modalText) {
        const { id, type, content } = file;
        if (type === 'text') {
            modalText.innerHTML = content;
            modalText.style.overflowY = 'scroll';
        } else if (type === 'image') {
            const image = new Image();
            image.src = `data:image/png;base64,${content}`;
            image.id = 'modalImage';
            image.style.maxWidth = '98%';
            modalText.innerHTML = '';
            modalText.appendChild(image);
            modalText.style.overflowY = 'hidden';
            enableZoomAndPan(image);
        }
        modal.style.display = 'flex';
        modal.style.alignItems = 'center';
        modal.style.justifyContent = 'center';
    }

    return file;
};

window.fileContent = fileContent;

function openModal(fileId) {
    const modal = document.getElementById('myModal');
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';

    const file = {
        messageType: "getFileContentById",
        params: {
            fileId: fileId,
        }
    };
    window.chrome.webview.postMessage(JSON.stringify(file));
}

function createModal() {
    if (!document.getElementById('myModal')) {
        const modal = document.createElement('div');
        modal.id = 'myModal';
        modal.className = 'modal';

        const modalContent = document.createElement('div');
        modalContent.id = 'modalContent';
        modalContent.className = 'modal-content';

        const closeModalSpan = document.createElement('span');
        closeModalSpan.className = 'close';
        closeModalSpan.innerHTML = '&times;';
        closeModalSpan.onclick = function () {
            modal.style.display = 'none';
        };

        const modalText = document.createElement('div');
        modalText.id = 'modalText';
        modalText.style.overflowY = 'auto';
        modalText.style.maxHeight = '500px';
        modalText.style.maxWidth = '95%';

        modalContent.appendChild(closeModalSpan);
        modalContent.appendChild(modalText);
        modal.appendChild(modalContent);
        document.body.appendChild(modal);

        window.onclick = function (event) {
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        };
    }
}

function enableZoomAndPan(image) {
    let scale = 1;
    let panning = false;
    let startX = 0;
    let startY = 0;
    let translateX = 0;
    let translateY = 0;

    image.onwheel = function (event) {
        event.preventDefault();
        const scaleAmount = -event.deltaY * 0.004;
        scale = Math.min(Math.max(.125, scale + scaleAmount), 4);
        image.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
    };

    image.onmousedown = function (event) {
        event.preventDefault();
        panning = true;
        startX = event.clientX - translateX;
        startY = event.clientY - translateY;
        image.style.cursor = 'grabbing';
    };

    image.onmousemove = function (event) {
        event.preventDefault();
        if (!panning) return;
        translateX = event.clientX - startX;
        translateY = event.clientY - startY;
        image.style.transform = `scale(${scale}) translate(${translateX}px, ${translateY}px)`;
    };

    image.onmouseup = function () {
        panning = false;
        image.style.cursor = 'grab';
    };

    image.onmouseleave = function () {
        panning = false;
        image.style.cursor = 'grab';
    };
}

function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

function FileDisplay(inputString) {
    const regex = /<filename ([^<>]+)><fileid (\d+)>/g;
    const fileSvg = `<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0 0 32 32">
        <path d="M 6 3 L 6 29 L 26 29 L 26 9.59375 L 25.71875 9.28125 L 19.71875 3.28125 L 19.40625 3 Z M 8 5 L 18 5 L 18 11 L 24 11 L 24 27 L 8 27 Z M 20 6.4375 L 22.5625 9 L 20 9 Z"></path>
    </svg>`;

    inputString = inputString.replace(regex, (match, filename, fileId) => {
        if (filename.length > 20) {
            filename = "..." + filename.slice(-20);
        }
        return `__FILE_PLACEHOLDER_START_${fileId}_${filename}__FILE_PLACEHOLDER_END__`;
    });

    inputString = escapeHtml(inputString);

    inputString = inputString.replace(/__FILE_PLACEHOLDER_START_(\d+)_(.+?)__FILE_PLACEHOLDER_END__/g, (match, fileId, filename) => {
        return `<div onclick='openModal(${fileId})' class='fileBlock'>${fileSvg} ${escapeHtml(filename)}</div>`;
    });

    createModal();

    return inputString;
}

